package com.sxt.controller;

import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.sxt.vo.ActiverUser;
import com.sxt.vo.UserVo;

@Controller
@RequestMapping("login")
public class LoginController {
	
	
	@RequestMapping("toLogin")
	public String toLogin() {
		return "login";
	}

	/**
	 * 完成登陆
	 */
	@RequestMapping("login")
	public String login(UserVo userVo,Model model,HttpSession session) {
		String msg = "";   
	    UsernamePasswordToken token = new UsernamePasswordToken(userVo.getUsername(), userVo.getUserpwd());  
	    Subject subject = SecurityUtils.getSubject();  
	    try {  
	        subject.login(token);  
	        if (subject.isAuthenticated()) {  
	        	ActiverUser user = (ActiverUser) subject.getPrincipal();//subject.getPrincipal();类型就是new SimpleAuthenticationInfo(user
	        	session.setAttribute("user", user.getCurrentUser());
	            return "list";  
	        }
	    } catch (IncorrectCredentialsException e) {  
	        msg = "登录密码错误. Password for account " + token.getPrincipal() + " was incorrect.";  
	        model.addAttribute("error", msg);  
	        System.out.println(msg);  
	    } catch (UnknownAccountException e) {  
	        msg = "帐号不存在. There is no user with username of " + token.getPrincipal();  
	        model.addAttribute("error", msg);  
	        System.out.println(msg);  
	    }
	    return "login"; 
	}
}
